# -*- coding: utf-8 -*-
import psycopg2

class db_con:
	def __init__(self, db_host, db_name, db_port, db_user, db_pwd):
		self.db_host = db_host
		self.db_name = db_name
		self.db_port = db_port
		self.db_user = db_user
		self.db_pwd = db_pwd
		self.db_connect()

	def db_connect(self):
		self.db = psycopg2.connect(
		database=self.db_name,
		user=self.db_user,
		password=self.db_pwd,
		host=self.db_host,
		port=self.db_port)


	def insert(self, sql):
		cursor = self.db.cursor()
		try:
			cursor.execute(sql)
			self.db.commit()
			mes = 1
		except Exception as e:
			print(e)
			self.db.rollback()
			mes = 0
		return mes
	def close(self):
		self.db.close

	def getResult(self, sql):
		cursor = self.db.cursor()
		try:
			cursor.execute(sql)
			result = cursor.fetchall()
			self.db.commit()
			return result
		except Exception as e:
			self.db.rollback()
			raise e
	def getCollect(self, sql):
		cursor = self.db.cursor()
		try:
			cursor.execute(sql)
			result = cursor.fetchall()
			self.db.commit()
		except Exception as e:
			self.db.rollback()
			raise e
		collect = []
		columns = cursor.description
		for data in result:
			dict = {}
			i = 0
			for c in columns :
				dict[c.name] = data[i]
				i=i+1
			collect.append(dict)
		cursor.close
		return collect
	def insert(self, sql):
		cursor = self.db.cursor()
		try:
			cursor.execute(sql)
			self.db.commit()
			mes = 1
		except Exception as e:
			print(e)
			self.db.rollback()
			mes = 0
		return mes
	def close(self):
		self.db.close

if __name__ == '__main__':
	sql = 'select * from financial_news_title limit 2'
	pgsql = db_con('192.168.150.136','postgres',5432,'gpadmin','gpadmin')
	print(pgsql.getCollect(sql))